import { useRequest } from 'ahooks';
import axios from 'axios';

function useCRUD(url: any) {
  const { run, data, loading, error } = useRequest(
    async (value: any) => {
      const res = await axios.get(url, { params: { ...value } });
      return res.data;
    },
    {
      manual: false,
      onSuccess: (res) => {
        console.log('success', res);
      },
      onError: (err) => {
        console.log('error', err);
      },
    },
  );
  //删除数据
  const deleteItem = async (id: any) => {
    await axios.delete(`${url}/${id}`);
    run({}); //重新请求数据
  };
  //过滤数据
  const filters = (value: any) => {
    run(value);
  };
  //重置表单
  const resetForm = () => {
    run({});
  };

  return {
    data,
    loading,
    error,
    deleteItem,
    filters,
    resetForm,
  };
}

export default useCRUD;
